#ifndef _JsonUtil_H_
#define _JsonUtil_H_
#include <iostream>
#include <map>
#include <string>
#include "json/json_reader.cpp"
#include "json/json_writer.cpp"
#include "json/json_value.cpp"

using namespace std;
class JsonUtil{
public:
	JsonUtil()=default;
	static string parse_operation(string json);
	static map<string,string> parse_param(string json);
	static string get_response_json(const string &message,bool success);
	static string map_to_json(map<string,string> jmap);
	static map<string,string> json_to_map(string json);
private:
	static void parse(string &json);
};
void JsonUtil::parse(string &json)
{
	cout<<"init json"<<endl; 
}
/**
*to get the operations value of the request
**/
string JsonUtil::parse_operation(string json)
{
	Json::Reader reader;
	Json::Value value;
	string operation;
	if (reader.parse(json, value))
	{
		operation= value["operation"].asString();
	}
	return operation;
}
/**
*to get the params  of the request
**/
map<string,string> JsonUtil::parse_param(string json)
{
	map<string,string> param;
	Json::Reader reader;
	Json::Value value;
	if(reader.parse(json,value))
	{
		Json::Value json_param=value["params"];
		Json::Value::Members param_members=json_param.getMemberNames(); 
		for(Json::Value::Members::iterator iter = param_members.begin(); iter != param_members.end(); ++iter)
		{
			string member_name= *iter;
			string value_str = json_param[member_name].asString();
			param.insert(make_pair(member_name,value_str));
		}
	}
	return param;
}

/**
*response the json result to front-end
**/
string JsonUtil::get_response_json(const string &message,bool success)
{
	Json::Value root;
	root["message"]=message;
	if(success)
		root["state"]="success";
	else
		root["state"]="failed";
	string result= root.toStyledString();
	return result;
}

string JsonUtil::map_to_json(map<string,string> jmap)
{
	Json::Value root;
	for(const pair<string,string> &p:jmap)
		root[p.first]=p.second;
	string result=root.toStyledString();
	return result;
}

map<string,string> JsonUtil::json_to_map(string json)
{
	map<string,string> param;
	Json::Reader reader;
	Json::Value value;
	if(reader.parse(json,value)){
		Json::Value::Members param_members=value.getMemberNames(); 
		for(Json::Value::Members::iterator iter = param_members.begin(); iter != param_members.end(); ++iter)
		{
			string member_name= *iter;
			string value_str = value[member_name].asString();
			param.insert(make_pair(member_name,value_str));
		}
	}
	return param;
}

#endif